1. Introduction
Singletons helps us to work with an instances of a class or object so we have a global state in our application
2. Learning Objectives
- To be able to describe the Pattern
- To know where applied.
3. Key Concepts
- Single instance that can be share through all the application.
- When instantiating a new instance we need to double check if there is already an instance of our class.
- Shouldn’t be modifiable
Object.freeze
to freeze the object to ensure is not modifiable- ES2015 are already module
- We don’t longer need to explicitly create singletons, because modules are singletons by default
- Tradeoffs : Global scope pollution. hard to test because having only one instance all the test rely on the modification on the previous test
- Singletons helps us to work with an instances of a class or object so we have a global state in our application
4. Examples and Practical Cases
- we can use singleton to connect to databases
let instance;
class DBConnection {
constructor(uri) {
if (instance) {
throw new Error('Only one connection can exist!');
}
this.uri = uri;
instance = this;
}
connect() {
this.isConnected = true;
console.log(`DB ${this.uri} has been connected!`);
}
disconnect() {
this.isConnected = false;
console.log('DB disconnected');
}
}
const databaseConnector = Object.freeze(new DBConnection());
const connection = databaseConnector;
5. Reflections and Synthesis
- Summary:
singletons are class or objects that are inmutable and its goals it’s to centralize a logic such as connecting to a DB. They only need to exist a single instance of our class - Open Questions:
Why modules are singletons by default?
6. Conclusion
A final recap and how it connects to your overall learning journey on FrontendMasters.
7. References and Additional Resources
- [[Module Pattern]] (Include links to external resources or documents that provide deeper insights into the topic)